package org.mii.safeguard_v1.tools.jfreechart;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ChartDeleter;
import org.mii.safeguard_v1.tools.jfreechart.utilities.ChartUtilities;

/**
 * 保存chart的class
 */
public class SaveChartService {

	public static String saveChartAsPNG(JFreeChart chart, int width,
			int height, ChartRenderingInfo info, HttpSession session)
			throws IOException {

		if (chart == null) {
			throw new IllegalArgumentException("Null 'chart' argument.");
		}
		createTempDir();
		String prefix = ChartConstants.tempFilePrefix;
		if (session == null) {
			prefix = ChartConstants.tempOneTimeFilePrefix;
		}
		File tempFile = File.createTempFile(prefix, ".png", new File(System
				.getProperty("java.io.tmpdir")));
		System.out.println(System.getProperty("java.io.tmpdir"));
		ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
		if (session != null) {
			SaveChartService.registerChartForDeletion(tempFile, session);
		}
		return tempFile.getName();

	}

	/**
	 * 保存chart的方法 参考ServletUtilities
	 */
	public static String saveChartAsPNG(JFreeChart chart, int width,
			int height, ChartRenderingInfo info, HttpSession session,
			HttpServletRequest request) throws IOException {

		if (chart == null) {
			throw new IllegalArgumentException("chart为空");
		}
		SaveChartService.createTempDir();
		Date date = new Date();
		String prefix = ChartConstants.SECURITY_SEX_QUALITY;
		if (session == null) {
			prefix = ChartConstants.SECURITY_SESSION_NULL;
		}
		String myDate = StringUtils.deleteWhitespace(date.toString());
		myDate = myDate.substring(myDate.length() - 4) + myDate.substring(0, 8)
				+ "-";
		// 以下列举获取路径的方法
		// 1、request.getSession().getServletContext().getRealPath("/")，获取该站点所在物理位置的完整绝对路径
		// 2、request.getContextPath()) 获取站点根目录
		// 3、new File("/").getAbsolutePath())
		// 4、ServletUtilities.class.getResource("/"))获取ServletUtilities类的所在站点的相对路径
		// 5、Thread.currentThread().getContextClassLoader().getResource("")) 同上
		File tempFile = File.createTempFile(prefix + myDate, ".png", new File(
				request.getSession().getServletContext().getRealPath("/")// 获取路径
						+ "JFreeChart/"));

		ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
		if (session != null) {
			SaveChartService.registerChartForDeletion(tempFile, session);
		}
		return tempFile.getName();

	}

	protected static void createTempDir() {
		String tempDirName = System.getProperty("java.io.tmpdir");
		if (tempDirName == null) {
			throw new RuntimeException("Temporary directory system property "
					+ "(java.io.tmpdir) is null.");
		}

		// create the temporary directory if it doesn't exist
		File tempDir = new File(tempDirName);
		if (!tempDir.exists()) {
			tempDir.mkdirs();
		}
	}

	protected static void registerChartForDeletion(File tempFile,
			HttpSession session) {

		// Add chart to deletion list in session
		if (session != null) {
			ChartDeleter chartDeleter = (ChartDeleter) session
					.getAttribute("JFreeChart_Deleter");
			if (chartDeleter == null) {
				chartDeleter = new ChartDeleter();
				session.setAttribute("JFreeChart_Deleter", chartDeleter);
			}
			chartDeleter.addChart(tempFile.getName());
		} else {
			System.out.println("Session is null - chart will not be deleted");
		}
	}
}
